﻿KISSY.add("fgt/ui/labelcloud", function (S) {
    function LabelCloud(id) {
        var self = this;
        self._init(id);
    }

    S.augment(LabelCloud, {
        _init: function (id) {
            var self = this,
                $ = S.all,
                container = $(id);
            self.container = container;
            self.width = container.width();
            self.height = container.height();

            self.rectArray = [];
        },

        _rand: function (num) {
            return parseInt(num * Math.random());
        },

        _add: function (node) {
            var self = this,
                cw = self.width,
                ch = self.height,
                w, h, left, top, right, bottom,
                tryCount = 20;
            w = node.width();
            h = node.height();
            left = self._rand(cw - w);
            top = self._rand(ch - h);
            right = left + w;
            bottom = top + h;

            while (self._check(left, top, right, bottom) === false) {
                left = self._rand(cw - w);
                top = self._rand(ch - h);
                right = left + w;
                bottom = top + h;

                if (--tryCount <= 0) {
                    break;
                }
            }

            node.css({ top: top, left: left, display: "block", position: "absolute" });
            self.rectArray.push({ left: left, top: top, right: right, bottom: bottom });


        },

        _check: function (left, top, right, bottom) {
            var self = this,
                rectArray = self.rectArray,
                i;
            for (i = 0; i < rectArray.length; ++i) {
                if (self._isIntersect(rectArray[i], { left: left, top: top, right: right, bottom: bottom }) === true) {
                    return false
                }
            }
            return true;
        },

        _isIntersect: function (rect1, rect2) {
            var maxLeft = Math.max(rect1.left, rect2.left),
                maxTop = Math.max(rect1.top, rect2.top),
                minRight = Math.min(rect1.right, rect2.right),
                minBottom = Math.min(rect1.bottom, rect2.bottom);

            if (maxLeft > minRight || maxTop > minBottom) {
                return false;
            }
            else {
                return true;
            }
        },

        render: function () {
            var self = this,
                container = self.container,
                labelItems = container.all(".label-item");

            labelItems.each(function (item) {
                self._add.call(self, item);
            }, self);
        }
    });

    return LabelCloud;
});